package com.tarena.lbs.marketing.web.repository.impl;

import com.tarena.lbs.common.marketing.converter.CouponCodeConverter;
import com.tarena.lbs.marketing.web.mapper.CouponCodeMapper;
import com.tarena.lbs.marketing.web.repository.CouponCodeRepository;
import com.tarena.lbs.pojo.marketing.bo.CouponCodeBO;
import com.tarena.lbs.pojo.marketing.dos.CouponCodeDO;
import com.tarena.lbs.pojo.marketing.param.CouponCodeParam;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CouponCodeRepositoryImpl implements CouponCodeRepository {

    private static final Integer NUM = 1000;

    @Resource
    private CouponCodeMapper couponCodeMapper;

    @Resource
    private CouponCodeConverter couponCodeConverter;

    @Async("asyncExecutor")
    @Override
    public void makeCouponCode(int pageStart,int pageNum,Integer couponId, Integer businessId) {
        log.info("makeCouponCode pageStart={} pageNum={}",pageStart,pageNum);
        List<CouponCodeDO> couponCodeDOList = new ArrayList<>();
        Date now = new Date();
        for (int i = pageStart; i < pageNum; i++) {
            CouponCodeDO param = new CouponCodeDO();
            param.setBusinessId(businessId);
            param.setCouponId(couponId);
            param.setCreateAt(now);
            param.setStatus(0);
            param.setCouponCode(UUID.randomUUID().toString().replaceAll("-", ""));
            couponCodeDOList.add(param);
        }
        couponCodeMapper.batchInsertCouponCode(couponCodeDOList);
        log.info("makeCouponCode end");
    }

    @Override
    public void batchInsertCouponCode(Integer couponId, Integer businessId, Integer totalNum) {
        int pageNum = (totalNum + NUM - 1) / NUM;
        for (int i = 0; i < pageNum; i++) {
            int pageStartNum = i * NUM;
            int pageEndNum = (i + 1) * NUM;
            if (i == pageNum - 1) {
                pageEndNum = totalNum;
            }
            makeCouponCode(pageStartNum,pageEndNum,couponId,businessId);
        }
    }

    @Override
    public void update(CouponCodeParam param) {
        CouponCodeDO couponCodeDO = new CouponCodeDO();
        BeanUtils.copyProperties(param, couponCodeDO);
        couponCodeMapper.updateByPrimaryKeySelective(couponCodeDO);
    }

    @Override
    public CouponCodeBO getCouponCodeDetail(Integer couponId) {
        return couponCodeConverter.do2bo(couponCodeMapper.getCouponCodeDetail(couponId));
    }
}
